package org.mihalovic.PES.Application;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.SplashScreen;

import java.io.File;
import javax.swing.JOptionPane;
import org.mihalovic.PES.GUI.AppWindow;
import org.mihalovic.PES.data.DataManager;


/**
 * @author Martin Mihalovic
 */
public class Main {

    /**
     * Application's entry point
     */
    public static void main(String[] args)
    {
        try {
            SplashScreen splash = SplashScreen.getSplashScreen();
            if(splash == null)
                throw new Exception("Splash screen image not found");
            
            Graphics2D graphics = splash.createGraphics();

            setSplashMessage(splash, graphics, "", 0.1);
            DataManager dbcm = new DataManager();

            setSplashMessage(splash, graphics, "Loading inverted index", 0.3);
            dbcm.LoadInvertedIndex(new File(AppConfiguration.ReadValue("indexFile")));
            
            setSplashMessage(splash, graphics, "Loading graph - edges", 0.5);
            dbcm.LoadRatings(new File(AppConfiguration.ReadValue("ratingsFile")));
            
            setSplashMessage(splash, graphics, "Loading graph - nodes", 0.7);
            dbcm.LoadUsers(new File(AppConfiguration.ReadValue("usersFile")));

            setSplashMessage(splash, graphics, "Loading domains", 0.9);        
            dbcm.LoadDomains(new File(AppConfiguration.ReadValue("domainsFile")));

            setSplashMessage(splash, graphics, "Starting GUI...", 0.955);
            AppWindow mw = AppWindow.getInstance();
            mw.SetSourceGraphReader(dbcm);
            mw.onSourceDataChange();
        }
        catch(Exception e) {
            StackTraceElement[] traces = e.getStackTrace();
            String stack = "";
            for(StackTraceElement element : traces)
                stack += element.toString() + "\n";

            JOptionPane.showMessageDialog(null, e.getMessage() + "\n" + stack, "Fatal error", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    
    private static void setSplashMessage(SplashScreen splash, Graphics2D graphics, String message, double percecnt){
        Rectangle rec = splash.getBounds();
        
        graphics.setComposite(AlphaComposite.Clear);
        graphics.fillRect(0, 0, rec.width, rec.height);     //Clear any previous content
        graphics.setPaintMode();
        graphics.setColor(Color.WHITE);
        graphics.drawString(message, 10, 15);
        graphics.fillRect(10, rec.height-30, (int)(percecnt * rec.width), 20);
        
        splash.update();
    }
}
